import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import * as fs from 'fs';
import * as path from 'path';

export interface EventData {
  id: string;
  type: string;
  data: any;
  timestamp: number;
}

@Injectable()
export class EventEmitterService {
  constructor(private eventEmitter: EventEmitter2) {}

  // private requests = {};

  emit(eventType: string, data: any): void {
    this.eventEmitter.emit(eventType, data);
    console.log(`[Event Emitted] ${eventType}:`, data);
  }

  on(eventType: string, callback: (event: EventData) => void): void {
    this.eventEmitter.on(eventType, callback);
    console.log(`[Event Listener Added] ${eventType}`);
  }

  once(eventType: string, callback: (event: EventData) => void): void {
    this.eventEmitter.once(eventType, callback);
    console.log(`[One-time Event Listener Added] ${eventType}`);
  }

  removeListener(
    eventType: string,
    callback: (event: EventData) => void,
  ): void {
    this.eventEmitter.removeListener(eventType, callback);
    console.log(`[Event Listener Removed] ${eventType}`);
  }

  removeAllListeners(eventType?: string): void {
    if (eventType) {
      this.eventEmitter.removeAllListeners(eventType);
      console.log(`[All Event Listeners Removed] ${eventType}`);
    } else {
      this.eventEmitter.removeAllListeners();
      console.log('[All Event Listeners Removed] All Events');
    }
  }

  solveRequest(uuid: string, requestId: string) {
    return new Promise((resolve, reject) => {
      this.once('request.completed', (event) => {
        console.log('event: ', event);
        const { data } = event;
        console.log('deleteRequest: requestId: ', requestId);
        // 删除文件
        const tempDir = path.join(process.cwd(), 'temp');
        const filePath = path.join(tempDir, `${uuid}__${requestId}__config`);
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath);
        }
        resolve(data);
        // }
      });
    });
  }

  addRequest(uuid: string, requestId: string, data: any) {
    // 保存 data 到本地文件
    try {
      const tempDir = path.join(process.cwd(), 'temp');
      if (!fs.existsSync(tempDir)) {
        fs.mkdirSync(tempDir, { recursive: true });
      }
      const filePath = path.join(tempDir, `${uuid}__${requestId}__config`);
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
      console.log('请求配置已保存到文件:', filePath);
    } catch (error) {
      console.error('保存请求配置文件失败:', error);
    }
  }

  deleteRequest(uuid: string, requestId: string) {
    // 删除本地文件
    const tempDir = path.join(process.cwd(), 'temp');
    const filePath = path.join(tempDir, `${uuid}__${requestId}__config`);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
  }

  getAllRequests(uuid: string) {
    const requests = {};
    // 读取本地文件
    const tempDir = path.join(process.cwd(), 'temp');
    const files = fs.readdirSync(tempDir);
    // 过滤出以 __config 结尾的文件
    const configFiles = files.filter(
      (file) => file.startsWith(`${uuid}__`) && file.endsWith('__config'),
    );
    for (const file of configFiles) {
      const filePath = path.join(tempDir, file);
      const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      // 获取文件名
      const uuidAndRequestId = file.split('__config')[0];
      const [uuid, requestId] = uuidAndRequestId.split('__');
      requests[`${uuid}__${requestId}`] = data;
    }
    return requests;
  }
}
